package com.resou.reader.bookshelf.bookedit;


import com.resou.reader.ReSouApplication;
import com.resou.reader.base.ResouBasePresenter;
import com.resou.reader.data.Injection;
import com.resou.reader.data.bookshelf.BookshelfRepository;
import com.resou.reader.data.local.LitePalHelper;
import com.resou.reader.bookshelf.readhistory.datasupport.BookCollection;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.eventbus.LoadBookEvent;


import org.greenrobot.eventbus.EventBus;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by ${Garrett} on 2018/9/7.
 * Contact me krouky@outlook.com
 */
public class BookShelfEditPresenter extends ResouBasePresenter<IBookShelfEditView> {

    private final BookshelfRepository mRepository;

    public BookShelfEditPresenter(IBookShelfEditView view) {
        super(view);
        mRepository = Injection.provideBookshelfRepository();
    }

    private static final String TAG = "BookShelfEditPresenter";

    /**
     * 获取书架列表
     */
    public void requestPursuitBookList() {
        mRepository.getBooks2(UserInstance.getToken())
                .subscribeOn(getIOSchedulers())
                .observeOn(getMainSchedulers())
                .subscribe(new Observer<List<BookCollection>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                    }

                    @Override
                    public void onNext(List<BookCollection> bookCollections) {
                        mView.setBookList(bookCollections);
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showError(e);
                    }

                    @Override
                    public void onComplete() {
                        mView.showContent();
                    }
                });
    }

    /**
     * 单个删除
     *
     * @param collection
     */
    public void delete(BookCollection collection) {
        addCompositeDisposable(
                Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
                    LitePalHelper.deleteBook(collection);

                    mRepository.delete(UserInstance.getToken(), collection.getBookId());

                    emitter.onNext(true);
                })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(bookCollections -> {
                            ToastUtil.makeShortToast("删除成功");
                            EventBus.getDefault().post(new LoadBookEvent());
                        })
        );
    }

    /**
     * 删除多个书籍
     *
     * @param collections
     */
    public void deleteAll(Set<BookCollection> collections) {
        mView.showProgress();
        /**
         * 构建书籍列表的字符串
         */
        StringBuilder stringBuilder = new StringBuilder();
        for (Iterator iterator = collections.iterator(); iterator.hasNext(); ) {
            BookCollection collection = (BookCollection) iterator.next();
            String bookId = collection.getBookId();
            stringBuilder.append(bookId);
            if (iterator.hasNext()) {
                stringBuilder.append(",");
            }
        }

        if (NetworkUtils.isNetworkConnected(ReSouApplication.getContext())) {
            if (UserInstance.isLogin()) {
                addCompositeDisposable(
                        mRepository.deleteBook(UserInstance.getToken(), stringBuilder.toString())
                                .subscribeOn(getIOSchedulers())
                                .observeOn(getMainSchedulers())
                                .subscribe(result -> {
                                    if (result.getCode() == 0) {
                                        mView.showSuccess();
                                        //删除本地
                                        for (BookCollection collection : collections) {
                                            LitePalHelper.deleteBook(collection);
                                        }
                                        EventBus.getDefault().post(new LoadBookEvent());
                                    }
                                }, throwable -> {
                                    mView.showFailed();
                                })
                );
            } else {
                for (BookCollection collection : collections) {
                    LitePalHelper.deleteBook(collection);
                }
                EventBus.getDefault().post(new LoadBookEvent());
                mView.showSuccess();
            }
        } else {
            for (BookCollection collection : collections) {
                LitePalHelper.deleteBook(collection);
            }
            EventBus.getDefault().post(new LoadBookEvent());
            mView.showSuccess();
        }
    }
}